package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScanPlus;
import com.heima.common.aliyun.GreenTextScanPlus;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xsz
 * @DateTime: 2024/1/30 22:12
 **/

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) throws Exception {
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);

        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }

        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){

            //从文章中提取文本内容和图片
            Map<String,Object> textAndImage = handleTextAndImages(wmNews);

            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImage.get("content"),wmNews);
            if(!isSensitive) return;

            //审核文本
            boolean isTextScan = handleTextSacn((String) textAndImage.get("content"),wmNews);
            if(!isTextScan)return;

            //审核图片
            boolean isImageScan = handleImageSacn((List<String>) textAndImage.get("images"),wmNews);
            if(!isImageScan)return;

            //审核成功，保存文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);

            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }

            //回填article_id

            wmNews.setArticleId((Long) responseResult.getData());

            updateWmNews(wmNews,(short) 9,"审核成功");

        }
    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理的敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList
                (Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否含有敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size()>0){
            updateWmNews(wmNews,(short) 2,"当前文章存在违规内容"+map);
            flag = false;
        }

        return flag;

    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 保存app段相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //set layout
        dto.setLayout(wmNews.getType());
        //set channel
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getId());
        if (wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //set author
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }

        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveArticle(dto);

        return responseResult;

    }

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScanPlus greenImageScanPlus;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核图片方法 违规返回false 不违规返回 true
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageSacn(List<String> images, WmNews wmNews) throws Exception {

        boolean flag = true;

        if(images == null || images.size() == 0){
            return true;
        }

        //下载图片
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);

                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(in);

                //图片识别
                String result = tess4jClient.doOCR(bufferedImage);
                //文字检测
                boolean isSensitive = handleSensitiveScan(result, wmNews);

                if(!isSensitive){
                    return false;
                }


                imageList.add(bytes);
            }

        }catch (Exception e){
            e.printStackTrace();
        }




        //greenImageScanPlus方法检测图片是否违规，如果违规则返回true
        if(greenImageScanPlus.greenImageScanPlus(imageList)){
            flag = false;
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
        }

        return flag;

    }


    @Autowired
    private GreenTextScanPlus greenTextScanPlus;


    /**
     * 审核文本方法
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextSacn(String content, WmNews wmNews) {

        boolean flag = true;
        if((wmNews.getTitle()+"-"+content).length() == 1){
            return true;
        }
        try{
            Map map = greenTextScanPlus.greenTextScanPlus(wmNews.getTitle()+"-"+content);
            if(map != null){
                if(map.containsKey("labels")){
                    String value = (String) map.get("labels");
                    if(!value.isEmpty()){
                        flag = false;
                        updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                    }
                }
                //if (map.get("labels") != null){
                //    flag = false;
                //    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                //}
            }

        }catch (Exception e){
            e.printStackTrace();
        }


        return flag;
    }

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 提取图片和文本
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存储文本
        StringBuilder stringBuilder = new StringBuilder();

        //存储图片
        List<String> images = new ArrayList<>();

        //从文章中提取文本和图片
        if(StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(),Map.class);
            for (Map map : maps) {
                if(map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                if(map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }

            //提取文章的封面图片
            if(StringUtils.isNotBlank(wmNews.getImages())){
                String[] split = wmNews.getImages().split(",");
                images.addAll(Arrays.asList(split));
            }

        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);

        return resultMap;

    }

}
